/**
 * Worker管理器 - 管理Web Worker的生命周期和通信
 */

class WorkerManager {
  constructor() {
    this.worker = null
    this.messageHandlers = new Map()
    this.isInitialized = false
    this.workerUrl = null
  }

  // 初始化Worker
  async init() {
    if (this.isInitialized) return this.worker

    try {
      // 创建Worker
      this.worker = new Worker(new URL('./timerWorker.js', import.meta.url))
      
      // 设置消息处理器
      this.worker.onmessage = this.handleWorkerMessage.bind(this)
      this.worker.onerror = this.handleWorkerError.bind(this)
      
      this.isInitialized = true
      console.log('Worker初始化成功')
      
      return this.worker
    } catch (error) {
      console.error('Worker初始化失败:', error)
      throw error
    }
  }

  // 处理Worker消息
  handleWorkerMessage(event) {
    const { type, id, data } = event.data
    
    // 查找对应的消息处理器
    const handler = this.messageHandlers.get(type)
    if (handler) {
      handler(id, data)
    }
    
    // 处理心跳消息
    if (type === 'HEARTBEAT') {
      // console.log('Worker心跳:', data.timestamp)
    }
  }

  // 处理Worker错误
  handleWorkerError(error) {
    console.error('Worker错误:', error)
    // 可以在这里实现错误恢复逻辑
  }

  // 注册消息处理器
  on(type, handler) {
    this.messageHandlers.set(type, handler)
  }

  // 移除消息处理器
  off(type) {
    this.messageHandlers.delete(type)
  }

  // 发送消息到Worker
  postMessage(type, id, data = {}) {
    if (!this.isInitialized || !this.worker) {
      throw new Error('Worker未初始化')
    }
    
    this.worker.postMessage({ type, id, data })
  }

  // 开始计时器
  startTimer(id, data) {
    this.postMessage('START_TIMER', id, data)
  }

  // 暂停计时器
  pauseTimer(id) {
    this.postMessage('PAUSE_TIMER', id)
  }

  // 继续计时器
  resumeTimer(id) {
    this.postMessage('RESUME_TIMER', id)
  }

  // 停止计时器
  stopTimer(id) {
    this.postMessage('STOP_TIMER', id)
  }

  // 开始倒计时
  startCountdown(id, data) {
    this.postMessage('START_COUNTDOWN', id, data)
  }

  // 暂停倒计时
  pauseCountdown(id) {
    this.postMessage('PAUSE_COUNTDOWN', id)
  }

  // 继续倒计时
  resumeCountdown(id) {
    this.postMessage('RESUME_COUNTDOWN', id)
  }

  // 停止倒计时
  stopCountdown(id) {
    this.postMessage('STOP_COUNTDOWN', id)
  }

  // 获取状态
  getStatus(id) {
    this.postMessage('GET_STATUS', id)
  }

  // 清理
  cleanup() {
    if (this.worker) {
      this.postMessage('CLEANUP')
      this.worker.terminate()
      this.worker = null
      this.isInitialized = false
      this.messageHandlers.clear()
    }
  }

  // 检查Worker是否可用
  isAvailable() {
    return this.isInitialized && this.worker && this.worker.readyState === 1
  }

  // 获取Worker状态
  getWorkerState() {
    if (!this.worker) return 'not_initialized'
    return this.worker.readyState === 1 ? 'running' : 'terminated'
  }
}

// 创建单例实例
const workerManager = new WorkerManager()

export default workerManager
